//package com.tduck.cloud.datav.data;
//
//import cn.hutool.cache.CacheUtil;
//import cn.hutool.cache.impl.TimedCache;
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.map.MapUtil;
//import cn.hutool.core.util.StrUtil;
//import com.google.common.collect.Lists;
//import com.tduck.cloud.datav.data.entity.GroupQueryParams;
//import com.tduck.cloud.datav.data.entity.GroupQueryResult;
//import com.tduck.cloud.datav.data.entity.QueryFieldListParams;
//import com.tduck.cloud.datav.entity.enums.AggsTypeEnum;
//import com.tduck.cloud.form.entity.enums.EsTypeEnum;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.elasticsearch.action.search.SearchRequest;
//import org.elasticsearch.action.search.SearchResponse;
//import org.elasticsearch.client.RequestOptions;
//import org.elasticsearch.client.RestHighLevelClient;
//import org.elasticsearch.index.query.BoolQueryBuilder;
//import org.elasticsearch.index.query.QueryBuilders;
//import org.elasticsearch.script.Script;
//import org.elasticsearch.search.SearchHit;
//import org.elasticsearch.search.SearchHits;
//import org.elasticsearch.search.aggregations.AggregationBuilders;
//import org.elasticsearch.search.aggregations.Aggregations;
//import org.elasticsearch.search.aggregations.BucketOrder;
//import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
//import org.elasticsearch.search.aggregations.bucket.terms.Terms;
//import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
//import org.elasticsearch.search.aggregations.metrics.ParsedValueCount;
//import org.elasticsearch.search.aggregations.metrics.ValueCountAggregationBuilder;
//import org.elasticsearch.search.builder.SearchSourceBuilder;
//import org.elasticsearch.search.collapse.CollapseBuilder;
//import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
//import org.springframework.data.elasticsearch.core.IndexOperations;
//import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
//import org.springframework.stereotype.Component;
//
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//
//@Component
//@RequiredArgsConstructor
//@Slf4j
//@Deprecated
//public class ElasticsearchTemplateImpl implements DataSearchTemplate {
//
//    private static final String keyword = ".keyword";
//    private final ElasticsearchRestTemplate template;
//    private final RestHighLevelClient restHighLevelClient;
//    //创建缓存，默认10分钟过期
//    TimedCache<String, Map<String, Object>> esIndexMappingCache = CacheUtil.newTimedCache(10 * 60 * 1000);
//
//
//    /**
//     * 是否是需要添加keyword
//     *
//     * @param indexName 索引名称
//     * @param fieldName 字段名称
//     */
//    private String addKeyword(String indexName, String fieldName) {
//        Map<String, Object> mappingProperties = null;
//        if (esIndexMappingCache.containsKey(indexName)) {
//            mappingProperties = esIndexMappingCache.get(indexName);
//        } else {
//            IndexCoordinates coordinates = IndexCoordinates.of(indexName);
//            IndexOperations indexOps = template.indexOps(coordinates);
//            if (!indexOps.exists()) {
//                return fieldName;
//            }
//            Map<String, Object> mapping = indexOps.getMapping();
//            mappingProperties = MapUtil.get(mapping, "properties", Map.class);
//        }
//        Map<String, Object> fieldProperties = MapUtil.get(mappingProperties, fieldName, Map.class);
//        String type = MapUtil.getStr(fieldProperties, "type");
//        // ES索引 text类型需要加.keyword才能等值查询 否则会被分词
//        return EsTypeEnum.TEXT.getType().equalsIgnoreCase(type) ? fieldName + keyword : fieldName;
//    }
//
//
//    @Override
//    public GroupQueryResult groupQuery(GroupQueryParams params) {
//        StringBuilder scriptStr = new StringBuilder();
//        // 分组字段
//        List<String> groupByFields = params.getGroupByFields();
//        for (int i = 0; i < groupByFields.size(); i++) {
//            String field = groupByFields.get(i);
//            scriptStr.append("doc['").append(addKeyword(params.getQueryObjName(), field)).append("']");
//            if (i < groupByFields.size() - 1) {
//                scriptStr.append("+'-'+");
//            }
//        }
//        Script script = new Script(scriptStr.toString());
//        TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("tag_tr").script(script).size(10000);
//        List<GroupQueryParams.Field> aggsFields = params.getAggsFields();
//        for (GroupQueryParams.Field field : aggsFields) {
//            // 排序后取前N个
//            aggregationBuilder.subAggregation(AggregationBuilders.count(field.getName() + "_" + field.getAggregateType()).field("id")).size(params.getLimit());
//        }
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.aggregation(aggregationBuilder);
//        //不输出元素数据
//        searchSourceBuilder.size(0);
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices(params.getQueryObjName());
//        searchRequest.source(searchSourceBuilder);
//        log.info("dsl:" + searchSourceBuilder);
//        SearchResponse response = null;
//        try {
//            response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        } catch (IOException e) {
//            log.error("groupQuery error", e);
//        }
//        Aggregations aggregations = response.getAggregations();
//        //获取配置
//        ParsedStringTerms parsedStringTerms = aggregations.get("tag_tr");
//        List<? extends Terms.Bucket> buckets = parsedStringTerms.getBuckets();
//        List<String> groupList = buckets.stream().map(item -> item.getKey().toString()).collect(Collectors.toList());
//        Map<String, List<Object>> groupAggsMap = new HashMap<>();
//        for (Terms.Bucket bucket : buckets) {
//            Aggregations bucketAggregations = bucket.getAggregations();
//            for (GroupQueryParams.Field field : aggsFields) {
//                String name = field.getName() + "_" + field.getAggregateType();
//                List<Object> list = groupAggsMap.get(name);
////                Aggregation aggregation = bucketAggregations.get(name);
//                ParsedValueCount cout = bucketAggregations.get(name);
//                if (null == list) {
//                    groupAggsMap.put(name, Lists.newArrayList(cout.getValue()));
//                } else {
//                    groupAggsMap.get(name).add(cout.getValue());
//                }
//            }
//        }
//        return new GroupQueryResult(groupList, groupAggsMap);
//    }
//
//    @Override
//    public long getFieldTotalValue(String indexName, String fieldName) {
//        ValueCountAggregationBuilder aggregation = AggregationBuilders.count("count").field(addKeyword(indexName, fieldName));
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        //默认按照聚合结果降序排序
//        searchSourceBuilder.size(0);
//        searchSourceBuilder.aggregation(aggregation);
//        //默认按照聚合结果降序排序
//        SearchRequest searchRequest = new SearchRequest(indexName);
//        searchRequest.source(searchSourceBuilder);
//        SearchResponse searchResponse = null;
//        try {
//            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        } catch (IOException e) {
//            log.error("getFieldValueCount error", e);
//        }
//        Aggregations aggregations = searchResponse.getAggregations();
//        return aggregations.<ParsedValueCount>get("count").getValue();
//    }
//
//    @Override
//    public long getFieldValueCount(String indexName, String fieldName, String value) {
//        String finalFieldName = addKeyword(indexName, fieldName);
//        BoolQueryBuilder filterQueryBuilder = QueryBuilders.boolQuery();
//        filterQueryBuilder.must(QueryBuilders.termQuery(finalFieldName, value));
//        ValueCountAggregationBuilder aggregation = AggregationBuilders.count("count").field(finalFieldName);
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        //默认按照聚合结果降序排序
//        searchSourceBuilder.size(0);
//        searchSourceBuilder.aggregation(aggregation);
//        //默认按照聚合结果降序排序
//        SearchRequest searchRequest = new SearchRequest(indexName);
//        searchSourceBuilder.query(filterQueryBuilder);
//        searchRequest.source(searchSourceBuilder);
//        SearchResponse searchResponse = null;
//        try {
//            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        } catch (IOException e) {
//            log.error("getFieldValueCount error", e);
//        }
//        Aggregations aggregations = searchResponse.getAggregations();
//        return aggregations.<ParsedValueCount>get("count").getValue();
//    }
//
//    @Override
//    public long getFieldValueCount(String indexName, String fieldName, AggsTypeEnum typeEnum) {
//        String finalFieldName = addKeyword(indexName, fieldName);
//        Script script = new Script(StrUtil.format("doc['{}']", finalFieldName));
//        BoolQueryBuilder filterQueryBuilder = QueryBuilders.boolQuery();
//        filterQueryBuilder.must(QueryBuilders.existsQuery(finalFieldName));
//        filterQueryBuilder.mustNot(QueryBuilders.termQuery(finalFieldName, ""));
//        TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("tag_tr").script(script).size(1).subAggregation(AggregationBuilders.count("count").field(finalFieldName));
//        if (typeEnum == AggsTypeEnum.MAX) {
//            aggregationBuilder.order(BucketOrder.aggregation("count", false));
//        } else if (typeEnum == AggsTypeEnum.MIN) {
//            aggregationBuilder.order(BucketOrder.aggregation("count", true));
//        }
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.aggregation(aggregationBuilder);
//        //不输出元素数据
//        searchSourceBuilder.size(0);
//        SearchRequest searchRequest = new SearchRequest();
//        searchRequest.indices(indexName);
//        searchRequest.source(searchSourceBuilder);
//        log.info("dsl:" + searchSourceBuilder);
//        searchSourceBuilder.query(filterQueryBuilder);
//        SearchResponse response = null;
//        try {
//            response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        Aggregations aggregations = response.getAggregations();
//        //获取配置
//        ParsedStringTerms parsedStringTerms = aggregations.get("tag_tr");
//        List<? extends Terms.Bucket> buckets = parsedStringTerms.getBuckets();
//        if (CollUtil.isNotEmpty(buckets)) {
//            return buckets.get(0).getAggregations().<ParsedValueCount>get("count").getValue();
//        }
//        return 0;
//    }
//
//    @Override
//    public List<Object> getFieldDistinctList(String indexName, String fieldName) {
//        SearchRequest searchRequest = new SearchRequest(indexName);
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.from(0);
//        sourceBuilder.size(1000);
//        String finalFieldName = addKeyword(indexName, fieldName);
//        //必须是keyword类型
//        sourceBuilder.collapse(new CollapseBuilder(finalFieldName));
//        searchRequest.source(sourceBuilder);
//        log.info("dsl:" + sourceBuilder);
//        SearchResponse search = null;
//        try {
//            search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        SearchHits hits = search.getHits();
//        SearchHit[] hits1 = hits.getHits();
//        List<Object> result = new ArrayList<>();
//        for (SearchHit hit : hits1) {
//            Object source = hit.getFields().get(finalFieldName).getValue();
//            if (null != source) {
//                result.add(source);
//            }
//        }
//        return result;
//    }
//
//    @Override
//    public List<Map<String, Object>> queryFieldList(QueryFieldListParams params) {
//        SearchRequest searchRequest = new SearchRequest(params.getQueryObjName());
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.from(0);
//        sourceBuilder.size(params.getLimit());
//        // params.getFields() 集合转数组
//        sourceBuilder.fetchSource(params.getFields().toArray(new String[0]), null);
//        searchRequest.source(sourceBuilder);
//        try {
//            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//            List<Map<String, Object>> list = new ArrayList<>();
//            for (SearchHit documentFields : response.getHits().getHits()) {
//                list.add(documentFields.getSourceAsMap());
//            }
//            return list;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//}
